<?php

namespace plugin\admin\app\controller;

use support\Request;
use support\Response;
use plugin\admin\app\model\AlarmNotification;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 预警通知 
 */
class AlarmNotificationController extends Crud
{
    
    /**
     * @var AlarmNotification
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new AlarmNotification;
    }


    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $query = $this->doSelect($where, $field, $order);
        $query = $query->with([
            'user' => function($q){
                $q->select('id', 'phone');
            },
            'device' => function($q){
                $q->select('id','gateway_id','sn');
            },
        ]);

        if($userPhone = $request->get('user_phone')){
            $query->leftJoin('wa_users as u', 'u.id','user_id')->where('u.phone', $userPhone);

        }

        $tempWhere = [];

        if($gatewayId = $request->get('gateway_id')){
            $tempWhere['d.gateway_id'] = $gatewayId;
        }

        if($sn = $request->get('sn')){
            $tempWhere['d.sn'] = $sn;
        }

        if(!empty($tempWhere)){
            $query->leftJoin('wa_devices as d', 'd.id','wa_alarm_notifications.device_id');

            if(!empty($tempWhere)){
                $query->where($tempWhere);
            }
        }

        return $this->doFormat($query, $format, $limit);
    }
    
    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('alarm-notification/index');
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('alarm-notification/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('alarm-notification/update');
    }

}
